import { api } from "@/global/utils/api"
import useApiPromiseHandler from "./api-promise-handler"
import { useI18n } from "vue-i18n" 
import { ref, watch } from 'vue';
import useStaff from "./staff";

export default function useFindArticles() {
  const { getLocalStaff } = useStaff();
  const { t } = useI18n();
  const departmentOnly = ref(false);
  const currentPage = ref(1);
  const PAGESIZE = 5;
  const isFetchingList = ref(false);
  const articleList = ref([]);
  const noMore = ref(false);

  watch(departmentOnly, (v, oldV) => {
    // 如果正在 fetching， 不允许改变这个行为
    if (isFetchingList.value) {
      departmentOnly.value = oldV;
      return;
    }
    console.log(v);
    noMore.value = false;
    articleList.value = [];
    currentPage.value = 1;
    fetch();
  })

  const findArticles = (page, countPerPage, departmentId, onSuccessed, onFaild) => {
    const url = departmentId == null ? `/articles/findAll/${page}/${countPerPage}` : `/articles/findAll/${page}/${countPerPage}/${departmentId}`;
    useApiPromiseHandler(t,
      api.get(url),
      onSuccessed, onFaild,
      () => isFetchingList.value = false
    )
  };

  const fetch = () => {
    if (noMore.value) return;
    isFetchingList.value = true;
    const departmentId = departmentOnly.value ? getLocalStaff().department.id : null;
    findArticles(currentPage.value, PAGESIZE, departmentId, (resp) => {
      resp.data.content.forEach(article => {
        articleList.value.push(article);
      });
      if (!resp.data.last)
        currentPage.value++;
      else 
        noMore.value = true;
    }, (err) => console.log(err));
  };

  const findOneContent = (articleId, onSuccessed, onFaild) => {
    useApiPromiseHandler(t,
      api.get(`/articles/findContent/${articleId}`),
      (resp) => {
        if (resp.data) 
          onSuccessed(resp.data)
        else onFaild("查询的文章内容不存在");
      },
      onFaild
    )
  }

  return { fetch, findOneContent, departmentOnly, currentPage, isFetchingList, articleList, noMore };
}